import getSchemeUri from "../gw/getSchemeUri";

function createIframe() {
	//添加iframe
	let iframe = document.createElement('iframe');
	iframe.style.display = 'none';
	document.body.appendChild(iframe);
	return iframe;
}

export function openBrowser() {
	//提示打开浏览器
	// MessageBox.alert('请在浏览器中打开！')
	let u = navigator.userAgent;
	let isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
	var Iosimgdiv = '<img class="Iosimgdiv" src="static/image/iOS.png"' +
		'style="width:100%;height:100%;">'
	var Androidimgdiv = '<img class="Androidimgdiv" src="static/image/Android.png"' +
		'style="width:100%;height:100%;">'
	let text = document.createElement("div");
	let textStyle = `width:100%;height:100%;position: fixed;top:0;z-index: 999999;`;
	text.setAttribute("style", textStyle);
	if(isIos) {
		text.innerHTML = Iosimgdiv;
		document.querySelector(".container-box").appendChild(text);
	} else if(isAndroid) {
		text.innerHTML = Androidimgdiv;
		document.querySelector(".container-box").appendChild(text);
	}
}

/**
 * 唤起app的方法，支持唤起对应页面
 * @param {Object} params {type: "RN" || "Webview", path: "h5页面路径或者rn应用的screen", ...其余参数}
 */
export function openApp(params = {}) {
	let downloadUrlForAndroid = `https://${location.hostname}/static/NJ/download/index.html`;
	// let downloadUrlForAndroid = `https://pre-njxs.weilian.cn/static/NJ/download/index.html`;
	// let downloadUrlForIOS = "https://itunes.apple.com/cn/app/%E5%AE%81%E5%AE%B6%E9%B2%9C%E7%94%9F/id1315875095?mt=8"
	let downloadUrlForIOS = `https://${location.hostname}/static/NJ/download/index.html`;
	// let localUrl = "ningjiaxiansheng://ningjiaxiansheng.app.com";
	let localUrl = getSchemeUri(params);
	let openIframe = createIframe();
	let u = navigator.userAgent;
	let isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
	let isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;
	// return console.log("localUrl", localUrl);
	if(isIos) {
		
		//判断是否是ios
		window.location.href = localUrl;
		let loadDateTime = Date.now();
		setTimeout(function() {
			let timeOutDateTime = Date.now();
			if(timeOutDateTime - loadDateTime < 2500) {
				window.location.href = downloadUrlForIOS;
			}
		}, 2000);
	} else if(isAndroid) {
		//判断是否是android
		if(isChrome) {
			console.log("ch-localUrl", localUrl);
			//chrome浏览器用iframe打不开得直接去打开，算一个坑
			window.location.href = localUrl;
		} else {
			//抛出你的scheme
			console.log("localUrl", localUrl);
			
			openIframe.src = localUrl;
		}
		setTimeout(function() {
			window.location.href = downloadUrlForAndroid;
		}, 500);
	} else {
		//主要是给winphone的用户准备的,实际都没测过，现在winphone不好找啊
		openIframe.src = localUrl;
		setTimeout(function() {
			window.location.href = downloadUrlForAndroid;
		}, 500);
	}
}